<template>
	<view class="background">

		<!-- <view class="info-list" @click="chooseAddress()">
			<view class="address-info">
				<view class="address">
					<uni-icons type="location" size="25" color="#ffd427"></uni-icons>
					{{ address[0].address }}
				</view>
				<view class="name-phone">{{ address[0].name }} {{ address[0].phone }}</view>
			</view>
		</view> -->
		<view class="info-list" @click="showAddressWindow">
			<view class="address-info">
				<view class="address">
					<uni-icons type="location" size="25" color="#ffd427"></uni-icons>
					{{ address[0].address }}
				</view>
				<view class="name-phone">{{ address[0].name }} {{ address[0].phone }}</view>
			</view>
		</view>
		<address-window ref="addressWindow" :addresses="Alladdress" @select="updateAddress" @close="hideAddressWindow"></address-window>
		
		
		<view class="store-list">
			<!-- 遍历商店列表 -->
			<view v-for="(store, storeIndex) in stores" :key="storeIndex" class="store">
				<view class="store-header">
					<!-- <image class="store-logo" :src=" store.logo "></image> -->
					<!-- 商店名称 -->
					<text class="store-name">{{ store.name }}</text>
					<uni-icons type="forward" size="18" class="right-arrow-icon"></uni-icons>
				</view>
				<!-- 遍历商店中的商品列表 -->
				<view v-for="(item, itemIndex) in store.cartItems" :key="itemIndex" class="item-row"
					@click="goToStoreDetail(store.id)">
					<!-- 商品信息 -->
					<view class="item-info">
						<!-- 商品图片 -->
						<image class="item-image" :src="item.image"></image>
						<!-- 商品名称、价格和数量 -->
						<view class="item-details">
							<!-- 商品名称 -->
							<text class="item-name">
								<view class="goods_name">{{ item.name }}</view>
							</text>
							<!-- 商品价格和数量容器 -->
							<view class="item-pricing-quantity">
								<!-- 商品价格 -->
								<text class="item-price">￥{{ item.price }}</text>
								<!-- 商品购买数量 -->
								<text class="item-quantity">x{{ item.quantity }}</text>
							</view>
						</view>
					</view>
				</view>

				<view class="store-footer">
					<text>实付款：</text>
					<text class="actual-payment">￥{{ totalAmounts[storeIndex].toFixed(2)}}</text>
				</view>
			</view>
		</view>

		<view class="service-list">
			<view class="service">
				<text class="item-service">宝贝服务</text>
				<view class="exchange-info">
					<view class="exchange"><uni-icons type="checkbox" size="20"
							class="right-arrow-icon"></uni-icons>七天无理由退换</view>
					<view><uni-icons type="checkbox" size="20" class="right-arrow-icon"></uni-icons>运费险</view>
				</view>
			</view>
		</view>

		<view class="service-list">
			<view class="service">
				<text class="problem">遇到问题？</text>
				<view class="service-info">
					<view class="servant"><uni-icons type="person-filled" size="20" class="right-arrow-icon"
							color="#ffd427"></uni-icons>淘工厂客服</view>
					<view class="complaint"><uni-icons type="chat" size="20" class="right-arrow-icon"
							color="#ffd427"></uni-icons>投诉商家</view>
				</view>
			</view>
		</view>

		<!--底部-->
		<view class="footer">
			<!-- <view class="footer-item">
				<text class="total-price">合计:<text class="total-price-color"></text></text>
			</view> -->
			<view class="footer-item">
				<button class="reorder-btn" @click="checkout()">
					提交订单
				</button>
			</view>
		</view>
	</view>
</template>

<script>
	import axios from 'axios';
	import service from '../../utils/request.js';
	import AddressWindow from '@/components/AddreessWindow.vue'
	export default {
		data() {
			return {
				userID: localStorage.getItem("userID"),
				address: {},
				Alladdress: {},
				stores: [{
					cartItems: [],
				}],
				total: 0
			};
		},
		components: {
			AddressWindow,
		},
		computed: {
			totalAmounts() {
				// 计算每个商店的总金额
				return this.stores.map(store => {
					return store.cartItems.reduce((total, item) => {
						return total + item.price * item.quantity;
					}, 0);
				});
			},
			total() {
				return this.totalAmounts.reduce((total, amount) => {
					return total + amount;
				}, 0).toFixed(2);
			},
		},
		onShow() {
			this.fetchAddress();
			this.getCartSelected();
			this.getAddressData();
		},
		methods: {
			showAddressWindow() {
				this.$refs.addressWindow.show();
			},
			hideAddressWindow() {
				this.$refs.addressWindow.closeWindow();
			},
			updateAddress(selectedAddress) {
				this.address = [selectedAddress];
			},
			async getAddressData() {
				try {
					const response = await service.get('/address/list/' + this.userID);
					// 确保返回的数据是数组格式
					if (Array.isArray(response.data)) {
						this.Alladdress = response.data;
					} else {
						console.error('返回的数据不是数组格式');
					}
					console.log('获取的数据:', response);
				} catch (error) {
					console.error('获取数据失败:', error);
				}
			},
			chooseAddress() {
				// 确保异步数据加载完成
				if (this.Alladdress && this.Alladdress.length > 0) {
					uni.showActionSheet({
						itemList: this.Alladdress.map(address => address.name || address), // 假设地址列表中包含name属性
						success: (res) => {
							// 更新当前地址信息
							const selectedAddress = this.Alladdress[res.tapIndex];
							this.address = [selectedAddress]; // 更新当前地址显示
							console.log('选中了地址:', selectedAddress);
						},
						fail: (res) => {
							console.error('操作菜单显示失败:', res.errMsg);
							// 可以在这里添加错误提示给用户
						}
					});
				} else {
					console.error('地址列表未加载或为空');
					// 可以在这里提示用户地址列表未加载或为空
				}
			},
			goTodeliveryList() {
				uni.navigateTo({
					url: '/pages/deliveryAddList/deliveryAddList'
				})
			},
			groupCartItemsBySeller(cartItems) {
				const stores = [];

				cartItems.forEach(item => {
					// 查找是否已经有相同sellerID的商店
					const store = stores.find(s => s.sellerID === item.sellerID);

					if (store) {
						// 如果商店已存在，添加商品到该商店的购物车项中
						store.cartItems.push({
							id: item.id,
							name: item.goodsName,
							price: item.price,
							image: '',
							quantity: item.num
						});
					} else {
						// 如果商店不存在，创建一个新的商店对象，并添加商品
						const newStore = {
							name: item.sellerName,
							cartItems: [{
								id: item.id,
								name: item.goodsName,
								price: item.price,
								image: '',
								quantity: item.num
							}],
							sellerID: item.sellerID // 添加sellerID以便后续查找
						};
						stores.push(newStore);
					}
				});

				return stores;
			},
			async fetchAddress() {

				try {
					const response = await service.get('/address/listDefault/' + this.userID);
					this.address = response.data;
					console.log('状态更新成功:', response);
				} catch (error) {
					console.error('状态更新失败:', error);
				}
			},
			async getCartSelected() {

				try {
					const response = await service.get('/cart/getSelected/' + this.userID);
					const cartItems = response.data;
					this.stores = this.groupCartItemsBySeller(cartItems);
					console.log('状态更新成功dasdasd:', stores);
				} catch (error) {
					console.error('状态更新失败dadadsa:', error);
				}
			},
			async checkout() {
				console.log('结算购物车中的商品');
				try {
					const responese = await service.post('/order/create', {
						receiverName: this.address[0].name,
						receiverPhone: this.address[0].phone,
						receiverAddress: this.address[0].address,
						userID: this.userID
					})
					uni.navigateTo({
						url: '/pages/order/order'
					})
					console.log('状态更新成功:', response);
				} catch (error) {
					console.error('状态更新失败:', error);
				}
			},

		},
		created() {
			const storeId = this.$route.params.storeId;
			this.fetchOrderDetails();
			// 使用storeId加载商店详情数据...
		},
	};
</script>

<style lang="scss" scoped>
	@use "order-confirm";
</style>